class Observer {
  constructor(data) {
    this.walk(data)
  }
  walk (data) {
    if (!data || typeof data !== 'object') return
    Object.keys(data).forEach(key => {
      this.defineReactive(data, key, data[key])
    })
  }
  defineReactive (obj, key, val) {
    const that = this
    // 如果val是对象，把val内部的属性转换成响应式数据
    this.walk(val)
    // dep: 收集依赖 发送通知
    const dep = new Dep()
    Object.defineProperty(obj, key, {
      get () {
        console.log('defineReactive get')
        Dep.target && dep.addSub(Dep.target)
        return val
        // return obj[key]  // 访问data[key]会访问此get方法,若返回obj[key]则会陷入死循环
      },
      set (newValue) {
        if (newValue === val) return
        console.log('defineReactive set:', newValue)
        val = newValue
        // this.walk(newValue) // this指向data对象
        that.walk(newValue)
        dep.notify()
      }
    })
  }
}